package com.hethongviet.job.helpers.download;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

//usually, subclasses of AsyncTask are declared inside the activity class.
//that way, you can easily modify the UI thread from here
public class DownloadFile extends AsyncTask<String, Integer, String>
{
	private ProgressDialog progressDialog = null;
	private String pathFile = null;
	private Activity activity = null;
	private int dilogId = -1;

	public static int _errorCode = -1;

	public static final int STATUS_NONE = 0;
	public static final int ERROR_CONNECTION = 1;
	public static final int ERROR_URL_NOT_EXIST = 2;
	public static final int STATUS_SUCCESS = 3;
	public static final int ERROR_FILE_CREATE = 4;

	public DownloadFile(Activity activity, ProgressDialog progressDialog,
			String pathFile, int dialogId)
	{
		this.pathFile = pathFile;
		this.progressDialog = progressDialog;
		this.activity = activity;
		this.dilogId = dialogId;
		_errorCode = STATUS_NONE;
	}

	@Override
	protected void onPreExecute()
	{
		super.onPreExecute();
	}

	@Override
	protected String doInBackground(String... aurl)
	{
		int count;

		try
		{
			Log.d("Debug", "11111111 download file: " + aurl[0]);
			URL url = new URL(aurl[0]);
			URLConnection conexion = url.openConnection();
			conexion.connect();
			Log.d("Debug", "11111111 ");
			int lenghtOfFile = conexion.getContentLength();

			InputStream input = new BufferedInputStream(url.openStream());
			Log.d("Debug", "1111111122222222 file="+pathFile);
			File file = new File(pathFile);
			File directory = file.getParentFile();
			
			Log.d("Debug", "1111111133333 path="+file.getParentFile());
			if (directory != null && !directory.exists() && !directory.mkdir())
			{
				Log.d("Debug", "11111111333333111111 cannot create directory!");
				_errorCode = ERROR_FILE_CREATE;
				return null;
			}
			
			Log.d("Debug", "1111111144444444444444 ");
			/*
			 * either no parent directories there or we have created missing
			 * directories
			 */
			if (file.createNewFile() || file.isFile())
			{
				/* ready to write your content */
				Log.d("Debug", "11111111555555555555 ");
				OutputStream output = new FileOutputStream(file);

				byte data[] = new byte[1024];

				long total = 0;
				Log.d("Debug", "111111116666666 ");
				while ((count = input.read(data)) != -1)
				{
					total += count;
					// publishProgress("" + (int) ((total * 100) /
					// lenghtOfFile));
					// android 3.0
					progressDialog.setProgress((int) ((total * 100) / lenghtOfFile));
					output.write(data, 0, count);
				}
				Log.d("Debug", "1111111177777777 ");
				output.flush();
				output.close();
				input.close();
				Log.d("Debug", "11111111888888888 ");
				if (total == 0)
				{
					_errorCode = ERROR_URL_NOT_EXIST;
				}
				else _errorCode = STATUS_SUCCESS;

			}
			else
			{
				Log.d("Debug", "11111111444444111111111 ");
				_errorCode = ERROR_FILE_CREATE;
			}

		} catch (FileNotFoundException e)
		{
			/* Connection error */
			e.printStackTrace();
			_errorCode = ERROR_URL_NOT_EXIST;

		} catch (Exception e)
		{
			/* URL not found */
			e.printStackTrace();
			_errorCode = ERROR_CONNECTION;
		}
		return null;

	}

	protected void onProgressUpdate(String... progress)
	{
		// mProgressDialog.setProgress(Integer.parseInt(progress[0]));
	}

	@Override
	protected void onPostExecute(String unused)
	{
		activity.dismissDialog(dilogId);
		if (_errorCode == ERROR_CONNECTION || _errorCode == ERROR_URL_NOT_EXIST)
		{
			activity.onWindowFocusChanged(true);
			return;
		}
	}
}
